package edu.iss.demo.web.controller;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.iss.demo.model.Employee;
import edu.iss.demo.service.EmployeeService;



@Controller
public class loginController {
	@Autowired
	private EmployeeService empservice;
	
	@RequestMapping(value = "/", method=RequestMethod.GET)
	public ModelAndView StartLogin()
	{
		ModelAndView mav=new ModelAndView();
		mav.setViewName("login");
		return mav;
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public ModelAndView check(@ModelAttribute @Valid Employee emp,BindingResult result,HttpServletRequest req,
			final RedirectAttributes rdr, WebRequest webRequest)
	{
		ModelAndView mav=new ModelAndView();
		Employee e=empservice.findById(emp.getEmployeeId());
		//System.out.println(e.getEmployeeId());
		
		if(e==null)
			{
				String message =  emp.getName()+ " : Pls Try Again !";
				rdr.addFlashAttribute("message", message);
				mav.setViewName("/login");
				return mav;
			}
		else{			
			req.getSession().setAttribute("loggedEmployee", e);
				if(e.getPassword().equals(emp.getPassword()))
				{
					if(e.getRole().equals("admin"))
					{
						mav.setViewName("redirect:/admin/managestaff");		
						return mav;
					}
					else if(e.getRole().equals("manager")){
						mav.setViewName("redirect:/manager/ApproveRejectLeave/"+emp.getEmployeeId());
						return mav;
					}
					else
					{
						mav.setViewName("redirect:/employee");
						return mav;
					}
				}	
				else{
					String message =   "  Pls Try Again !";
					rdr.addFlashAttribute("message", message);	
					mav.setViewName("/login");
					return mav;
				}
			}
		
	}
}
